<?php
require_once(dirname(__FILE__).'/Abstract.php');
	
/**
 * AccountService
 * 
 * Allows user to create an account, sign in, sign out and retrieves password
 * 
 * @package Seowebd : Medic - Online
 * @author Seowebd
 * @copyright 2014
 * @version $Id$
 * @access public
 */
class AccountService extends AbstractUserController 
{
	public function indexAction()
	{
		$this->signInAction();
	}
    
    /**
     * AccountService::signUpAction()
     * Controller for registration. A user will registred only as a patient
     * 
     * @return void
     */
    public function signUpAction() 
    {
        // Check if the user is connected
        if ($this->session->userdata('id_user')) {
            $this->session->set_flashdata('errorMessage', $this->l('You are not allowed for this request.'));
        	redirect('');
            die();
        }
        
    	$d = array();
		$d['title'] = $this->l('Sign Up');
		
        // On submit
    	if ($this->input->post('btn_submit') !== false){
            // Initialized the form validation
            $config = array(
               array(
                     'field'   => 'firstname', 
                     'label'   => $this->l('First name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'lastname', 
                     'label'   => $this->l('Last name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'email', 
                     'label'   => $this->l('Email'), 
                     'rules'   => 'trim|required|is_unique[medic_user_entity.email]|valid_email|xss_clean'
                  ),
               array(
                     'field'   => 'username', 
                     'label'   => $this->l('Username'), 
                     'rules'   => 'trim|required|alpha_dash|is_unique[medic_user_entity.username]|min_length[5]|xss_clean'
                  ),
               array(
                     'field'   => 'passwd', 
                     'label'   => $this->l('Password'), 
                     'rules'   => 'trim|required|matches[confirm_password]|min_length[5]|xss_clean'
                  ),
               array(
                     'field'   => 'confirm_password', 
                     'label'   => $this->l('Password confirmation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
			
			if ($this->form_validation->run() == FALSE ){
				$this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
            	$this->load->model('ORM/User/UserEntityORM');
				
                // Initialize the new record
                $record = array(
					'email'     => $this->input->post('email'),
					'username'  => $this->input->post('username'),
					'firstname' => $this->input->post('firstname'),
					'lastname'  => $this->input->post('lastname'),
					'passwd'    => sha1(UserEntityORM::PASSWD_PREFIX . $this->input->post('passwd')),
                    
                    // Automatic fill
					'id_role'      => 1,                             // By default, it is a patient
					'activated'    => 0,                             // The account is not yet activated
					'is_connected' => 0,                             // The user is not connected
					'token'        => md5(uniqid(rand(0, 9999))),    // Generating the token to activate the account
					'last_activity'  => @date('Y-m-d H:i:s'),
					'last_connexion' => null,
					'date_add'       => @date('Y-m-d H:i:s'),
					'date_upd'       => @date('Y-m-d H:i:s'),
				);
				
                // Create the new account
                if ($this->UserEntityORM->save($record)) {
                    // Send the confirmation mail
                    $params = array(
                        'receiver' => $record['firstname'],
                        'fromName' => $this->config->item('mail_from_name'),
                        'from'     => $this->config->item('mail_from'),
                        'subject'  => $this->l('Confirm your account'),
                        'to'       => $record['email'],
                        
                        // Params for the view
                        'token'    => $record['token'],
                        'validation_link' => base_url('User/MyAccount/Confirmation/?username='. $record['username'] .'&token='.$record['token']),
                    );
                    if ($this->renderMail($params, 'ConfirmSignUp')) {
                        $this->session->set_flashdata('successMessage', $this->l('Your account was successfully created. Check your mail to confirm your account.'));
                    } else {
                        $this->session->set_flashdata('errorMessage', $this->l('Your account was successfully created. But the mail of confirmation was not sent. Please contact our technical team.'));
                    }
                    
                    // Redirect to the sign in form
    				redirect('User/AccountService/signIn');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your account. Please try again or contact us.'));
                }
            }
    	}
        
        $d['title_for_layout'] = $this->l('You are a patient? Create your account now.');
        $d['menu'] = 'user';
        $d['page_name'] = 'signup';
        
        $this->load->view('Templates/Layouts/authLayout/header', $d);
        $this->load->view('User/AccountService/signUp', $d);
        $this->load->view('Templates/Layouts/authLayout/footer', $d);
    }
	
	public function signInAction()
    {
        // Check if the user is connected
        if ($this->session->userdata('id_user')) {
            $this->session->set_flashdata('errorMessage', $this->l('You are not allowed for this request.'));
        	redirect('');
            die();
        }
        
    	$d = array();
		$d['title'] = $this->l('Sign In');
		
        // On submit
    	if ($this->input->post('btn_submit') !== false){
            // Initialized the form validation
            $config = array(
               array(
                     'field'   => 'username', 
                     'label'   => $this->l('Username'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'passwd', 
                     'label'   => $this->l('Password'), 
                     'rules'   => 'trim|required|xss_clean'
                  )
            );
            $this->form_validation->set_rules($config);
			
			if ($this->form_validation->run() == FALSE ){
				$this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
				$this->load->model('ORM/User/UserEntityORM');
                $passwd = sha1(UserEntityORM::PASSWD_PREFIX . $this->input->post('passwd'));
				$user = $this->UserEntityORM->getByUsernameAndPasswd($this->input->post('username'),  $passwd);
                
                if ($user) {
                    if ($user->enabled) {
                        if ($user->activated == 2) {
                            // Connection in success
                            $record = array(
                                'id_user'       => $user->id_user, 
                                'is_connected'  => 1, 
                                'last_connexion'=> @date('Y-m-d H:i:s') ,
                                'last_activity' => @date('Y-m-d H:i:s') 
                                );
                            $this->UserEntityORM->save($record);
                            
                            $session_data = array(
                                'id_user'   => $user->id_user, 
                                'id_role'   => $user->id_role,
                                'username'  => $user->username,
                                'email'     => $user->email,
                                'firstname' => $user->firstname,
                                'lastname'  => $user->lastname,
                                'activated' => $user->activated,
                                'enabled'   => $user->enabled,
                            );
                            $this->session->set_userdata($session_data);
                            $this->session->set_flashdata('successMessage', $this->l('You are successfully signed in.'));
            				redirect('User/MyAccount/');
                            die();
                        } elseif ($user->activated == 1) {
                            $this->session->set_flashdata('errorMessage', $this->l('Your account is not yet activated.'));
                        } elseif ($user->activated == 0) {
                            $this->session->set_flashdata('errorMessage', $this->l('You should confirme your account. Please check your mail.'));
                        }
                    } else {
                        $this->session->set_flashdata('errorMessage', $this->l('Your account is disabled. Contact Medic Administration TEAM for more information.'));
                    }
                        
                } else {
                    // Connexion failed
                    $this->session->set_flashdata('errorMessage', $this->l('Sign in failed.'));
                }
            }
		}
        
        $d['title_for_layout'] = $this->l('Sign into Medic Center');
        $d['menu'] = 'user';
        $d['page_name'] = 'signin';
        
        $this->load->view('Templates/Layouts/authLayout/header', $d);
        $this->load->view('User/AccountService/SignIn', $d);
        $this->load->view('Templates/Layouts/authLayout/footer', $d);
	}
	
	public function signOutAction()
    {
        // Check if the user is connected
        if ($this->session->userdata('id_user')) {
            $this->session->sess_destroy();
            $this->session->set_flashdata('successMessage', $this->l('Disconnected successfully.'));
        	redirect('User/AccountService/signIn');
            die();
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('You are not allowed for this request.'));
            redirect('User/AccountService/signIn');
            die();
        }
	}
	
	public function passwordRecoveryAction()
    {
    	$d = array();
		$d['title'] = $this->l('Password Recovery');
        
        // Check if the user is connected
        if ($this->session->userdata('id_user')) {
            $d['connected']    = true;
            $_POST['id_user']  = $this->session->userdata('id_user');
            $_POST['username'] = $this->session->userdata('username');
        } else {
            $d['connected']    = false;
        }
		
        // On submit
    	if ($this->input->post('btn_submit') !== false){
            // Initialized the form validation
            $config = array(
               array(
                     'field'   => 'username', 
                     'label'   => $this->l('Username'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'passwd', 
                     'label'   => $this->l('The new password'), 
                     'rules'   => 'trim|required|matches[passwd_confirm]|min_length[5]|xss_clean'
                  ),
               array(
                     'field'   => 'passwd_confirm', 
                     'label'   => $this->l('Password confirmation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            
            // If the user is connected, he should provide the current password.
            if ($d['connected']) {
                $config[] = array(
                     'field'   => 'passwd_old', 
                     'label'   => $this->l('The old password'), 
                     'rules'   => 'trim|required'
                  );
            }
            $this->form_validation->set_rules($config);
			
			if ($this->form_validation->run() == FALSE ){
				$this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
				$this->load->model('ORM/User/UserEntityORM');
                $passwd = sha1(UserEntityORM::PASSWD_PREFIX . $this->input->post('passwd'));
                
                // Check the associated account
                if ($this->session->userdata('id_user')) {
                    // Check the user by id_user and username, if a session is active
    				$user = $this->UserEntityORM->getByIdUserAndUsername($this->session->userdata('id_user'), $this->input->post('username'));
                } else {
                    $user = $this->UserEntityORM->getByUsername($this->input->post('username'));
                }
                
                if ($user) {
                    // The account exist
                    $user->passwd        = $passwd;
                    $user->last_activity = @date('Y-m-d H:i:s');
                    $user->date_upd      = @date('Y-m-d H:i:s');
                    
                    if ($this->UserEntityORM->save((array)$user)) {
                        // Send a mail for notifying the password retrieves 
                        $params = array(
                            'receiver' => $user->firstname,
                            'fromName' => $this->config->item('mail_from_name'),
                            'from'     => $this->config->item('mail_from'),
                            'subject'  => $this->l('Your password was reset.'),
                            'to'       => $user->email,
                            
                            // Params for the view
                            'password' => $this->input->post('passwd'),
                        );
                        if ($this->renderMail($params, 'PasswordRecovery')) {
                            $this->session->set_flashdata('successMessage', $this->l('Your password was successfully reset.'));
                        } else {
                            $this->session->set_flashdata('errorMessage', $this->l('Your password was successfully reset. But an error occured will sending notification.'));
                        }
                        
        				redirect('User/MyAccount/');
                        die();
                    } else {
                        $this->session->set_flashdata('errorMessage', $this->l('An error occured while updating your password.'));
                    }
                } else {
                    // Connexion failed
                    $this->session->set_flashdata('errorMessage', $this->l('Sign in failed.'));
                }
            }
		}
        
        $d['title_for_layout'] = $this->l('Retreives your password');
        $d['menu'] = 'user';
        $d['page_name'] = 'password';
        
        $this->load->view('Templates/Layouts/authLayout/header', $d);
        $this->load->view('User/AccountService/PasswordRecovery', $d);
        $this->load->view('Templates/Layouts/authLayout/footer', $d);
	}
}

